<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Booth Products Controller
 *
 * @category
 * @package   
 * @author     Phạm Ngọc Khánh <phamngockhanh262@gmail.com>
 */
class Booth_product extends CI_Controller 
{	
	private $_data;
		
  	function __construct()
  	{
  		parent::__construct();
  	    $this->load->model('booth_products_model');
  	}
  	
	public function index($id)
	{   
	    $data['products'] = $this->booth_products_model->getListBoothProducts(array('where' => " AND category_id={$id}"));
        $this->load->view('booth/products/index', $data);
	}
	
	public function getBoothProductJson($param = NULL)
	{   
		$id = str_replace('product-edit-', '', $param);
	    $product = $this->booth_products_model->getBoothProductById($id);
		echo json_encode($product);
	}

	public function add($booth_products_id = NUll)
	{
	  $this->load->helper('frontend');
	  $this->load->helper('booth');
	  $this->load->library(array('form_validation'));
	  
	  
	  $this->form_validation->set_rules('product_type', 'product_type', 'trim|integer');
	  $this->form_validation->set_rules('intro_video', 'intro_video', 'trim|xss_clean');
	  $this->form_validation->set_rules('name', 'name', 'trim|xss_clean');
	  $this->form_validation->set_rules('price', 'price', 'trim|integer');
	  $this->form_validation->set_rules('base_price', 'base_price', 'trim|integer');
	  $this->form_validation->set_rules('warranty', 'warranty', 'trim|integer');
	  $this->form_validation->set_rules('status', 'status', 'trim|integer');
	  $this->form_validation->set_rules('forms', 'forms', 'trim|integer');
	  $this->form_validation->set_rules('made_in', 'made_in', 'trim|xss_clean');
	  $this->form_validation->set_rules('shipping', 'shipping', 'trim|integer');
	  $this->form_validation->set_rules('quantity', 'quantity', 'trim|integer');

	  if ($this->form_validation->run() == FALSE) { // not validate form
	      $this->session->set_flashdata('message', 'Một giá trị nhập vào form là không đúng định dạng');
	      redirect('booth/add');
	      
	      return FALSE;
	  } else {
	      $this->load->helper('controller');
	    
	      $_POST['slug'] = generalSlug($_POST['name']);
	      
	  	  if (isset($_POST['avatar-addCropJson'])) {
	  	      $avatarAddCropJson = $_POST['avatar-addCropJson'];
	          unset($_POST['avatar-addCropJson']);
	      } elseif (isset($_POST['avatar-editCropJson'])) {
	  	      $avatarEditCropJson = $_POST['avatar-editCropJson'];
	          unset($_POST['avatar-editCropJson']);
	      }
	      
	  	  if (isset($_POST['album-addCropJson'])) {
	  	      $albumAddCropJson = $_POST['album-addCropJson'];
	          unset($_POST['album-addCropJson']);
	      } elseif (isset($_POST['album-editCropJson'])) {
	  	      $albumEditCropJson = $_POST['album-editCropJson'];
	          unset($_POST['album-editCropJson']);
	      }
	      
	      if (!isset($_POST['make_as_homepage'])) {
	          $_POST['make_as_homepage'] = 0;
	      }
	      
	      if (isset($booth_products_id)) {
	          $this->booth_products_model->update($booth_products_id, $_POST);
	          $this->session->set_flashdata('message', 'Đã thay đổi thành công!');
	      } else {
	          $booth_products_id = $this->booth_products_model->create($_POST);
	          $this->session->set_flashdata('message', 'Đã thêm mới thành công!');
	      }
	      
	  	  if (isset($avatarAddCropJson) && $avatarAddCropJson) {
	          $this->addFile('avatar', $avatarAddCropJson, $booth_products_id);
	      }	elseif (isset($avatarEditCropJson) && $avatarEditCropJson) {
	          $this->addFile('avatar', $avatarEditCropJson, $booth_products_id);
	      }
	      
	  	  if (isset($albumAddCropJson) && $albumAddCropJson) {
	          $this->addFile('album', $albumAddCropJson, $booth_products_id);
	      }	elseif (isset($albumEditCropJson) && $albumEditCropJson) {
	          $this->addFile('album', $albumEditCropJson, $booth_products_id);
	      }
	      
	      redirect('booth/add');
	      
	      return TRUE;
	  }
	}
	
	public function addFile($type, $dataCrop, $booth_products_id)
	{
	    $data = ''; // file album to insert db
	    $this->load->library('image_lib');
	    
	    if ($type == 'album') {
	        $files = json_decode($dataCrop, TRUE);
	        $width = 626;
	        $height = 379;
	    } else if ($type == 'avatar') {
	        $files = json_decode($dataCrop, TRUE);
	        $width = 224;
	        $height = 155;
	    }
	
	    $tempPath = 'upload/booth/' . $_SESSION['userLoggedIn']['id'] . '/products/' . session_id() . '/' . $type . '/';
	    $path = 'upload/booth/' . $_SESSION['userLoggedIn']['id'] . '/products/' . $type . '/' . $booth_products_id . '/';
    	if (!file_exists($path)) {
  	        $old = umask(0);
            @mkdir($path, 0777, true);
            umask($old);
  	    }
	    
        //1. remove all file if edit
        if (isset($_POST['booth_products_id'])) {
            $dir_handle = @opendir($path) or die("Unable to open $path");
            while ($file = readdir($dir_handle)) {
                if($file == "." || $file == ".." || $file == "index.php" )
                    continue;
                unlink($path . $file);
            }
            closedir($dir_handle);
        }
	
        foreach ($files as $fileName => $fileData ) {
          // 2.crop image
          $this->image_lib->initialize(array(
              'image_library' => 'gd2',
              'source_image' => $tempPath . $fileName,
              'width' => $fileData['w'],
              'height' => $fileData['h'],
              'x_axis' => $fileData['x'],
              'y_axis' => $fileData['y'],
              'maintain_ratio' => FALSE
          ));
        
          if (!$this->image_lib->crop()) {
            $this->session->set_flashdata('message', $this->image_lib->display_errors());
            redirect('booth/add');
            return FALSE;
          } else {
            // 3.resize image
            $this->image_lib->initialize(array(
                'image_library' => 'gd2',
                'source_image' => $tempPath . $fileName,
                'new_image' => $path . $fileName,
                'width' => $width,
                'height' => $height,
                'maintain_ratio' => TRUE
            ));
            if (!$this->image_lib->resize()) {
              $this->session->set_flashdata('message', $this->image_lib->display_errors());
              redirect('booth/add');
              return FALSE;
            }
          }
          $this->image_lib->clear();
          // 4.remove temp file
          unlink($tempPath . $fileName);
        
          $data .= $fileName . ';';
        }
        $data = trim($data, ";");
	
        // remove temp dir
        @rmdir($tempPath);
        
	    // 5.update to db
	    $this->booth_products_model->update($booth_products_id, array($type => $data));
	}
	
    public function ajaxProductUploadFile($type)
	{
	    $fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
    	if ($fn) {
    	    // made temp dir
    	    $dir = 'upload/booth/' . $_SESSION['userLoggedIn']['id'] . '/products/' . session_id() . '/' . $type . '/';
    	    if (!file_exists($dir)) {
    	        $old = umask(0);
                @mkdir($dir, 0777, true);
                umask($old);
    	    }
    	
    	    file_put_contents(
    	        $dir . $fn,
    	        file_get_contents('php://input')
    	    );
    	
    	    echo "$fn uploaded";
    	    exit();
    	}
	}
	
	public function ajax_get_products_by_category_id($category_id = NULL)
	{   	    
	    $this->load->helper('frontend');
	    
	    $category_id = (int) $category_id;
	    $data['arr_products'] = $this->booth_products_model->get_products_by_category_id($category_id);
		
	    $this->load->view('booth/products/ajax_products', $data);
	}
}